<template>
  <div class="add_acount">
    <!-- 记账类型 -->
    <div class="type_time">
      <div class="type" @click="chooseAcountType">
        <div class="type_item" acountType="1" :class="{ choose_type_in: from.acountType == '1' }">
          支出
        </div>
        <div class="type_item" acountType="2" :class="{ choose_type_out: from.acountType == '2' }">
          收入
        </div>
      </div>
      <div class="time" @click="show = true">
        <span>{{ from.beginTime[0] }}-{{ from.beginTime[1] }}-{{
        from.beginTime[2]
      }}</span>
        <van-icon name="play" class="icon" size="15" />
      </div>
    </div>
    <div style="height: 0.5rem"></div>
    <!-- 钱框 -->
    <van-cell-group>
      <van-cell center>
        <!-- 使用 title 插槽来自定义标题 -->
        <template #title>
          <span class="custom_title_money" style="font-size: 0.9231rem">￥</span>
        </template>
        <!-- 使用 right-icon 插槽来自定义右侧图标 -->
        <template #right-icon>
          <span class="custom_title_money" v-if="from.number != ''">{{
        from.number
      }}</span><span class="custom_title_money_tip" v-else>请输入金额</span>
        </template>
      </van-cell>
      <van-field v-model="from.remask" rows="2" autosize label="备注" type="textarea" maxlength="50" placeholder="请输入备注"
        show-word-limit @blur="onBlur" @focus="onFocus" />
    </van-cell-group>
    <!-- 类型 -->
    <div class="useType">
      <div class="use_item" v-for="(item, index) in typeList" :key="index" @click="changeType(item, index)">
        <span class="iconfont" :class="item.icon" :style="{ color: item.choose ? '#38BE77' : '' }"></span>
        <span :style="{ color: item.choose ? '#38BE77' : '' }">{{
        item.name
      }}</span>
      </div>
    </div>
    <van-divider>银行卡</van-divider>
    <!-- 消费的卡 -->
    <div class="use_card" v-loading="loading">
      <van-swipe class="my-swipe" indicator-color="white" :loop="false">
        <van-swipe-item v-for="item in cardList" :key="item.id">
          <div class="use_card_item" @click="chooseCard(item)"
            :style="{ backgroundColor: from.card_id == item.id ? item.card_color : '#EFF1F3' }">
            <div class="card_img">
              <img :src="item.card_avatar" alt="" />
            </div>
            <div class="card_info_name">{{ item.card_name }}</div>
            <!-- 余额 -->
            <div class="card_info_money">{{ formatMoneyNum(item.current_amount) }}</div>
          </div>
        </van-swipe-item>
        <template #indicator="{ active, total }">
          <div class="custom-indicator">{{ active + 1 }}/{{ total }}</div>
        </template>
      </van-swipe>

    </div>
    <!-- 数字键盘 -->
    <van-number-keyboard :show="showkeyboard" theme="custom" extra-key="." close-button-text="完成" @input="onInput"
      @delete="onDelete" @blur="onComplete" :blur-on-close="true" :hide-on-click-outside="false" />
    <!-- 日期选择器 -->
    <van-popup v-model:show="show" position="bottom" :style="{ padding: '15px', height: '40%' }" round>
      <van-date-picker @confirm="onConfirm" @cancel="onCancel" v-model="currentDate" title="选择年月" :max-date="new Date()"
        :columns-type="['year', 'month', 'day']" />
    </van-popup>
    <!-- 遮罩层 -->
    <van-overlay :show="loading" @click="loading = false" z-index="10000">
      <div class="wrapper" @click.stop>
        <van-loading size="30px" vertical color="#0094ff">加载中...</van-loading>
      </div>
    </van-overlay>
  </div>
</template>

<script setup>
import { showToast } from "vant";
import { addAccountReq, queryCardList } from "@/api/index.js";
import { reactive, onMounted, ref } from "vue";

const emits = defineEmits("successAdd");


const loadingv2 = ref(false)
const cardList = ref([])
// 查询卡列表
const queryCardList_ = async () => {
  loadingv2.value = true
  const userInfo = localStorage.getItem("userInfo");
  const uid = JSON.parse(userInfo).id;
  const res = await queryCardList(uid)
  loadingv2.value = false
  if (res.status == 200) {
    console.log("查询卡列表成功:", res.data);
    cardList.value = res.data
  }
  else {
    showToast({
      message: "查询卡列表失败",
      duration: 2000,
      forbidClick: true,
    })
  }
}
// 格式化钱
const formatMoneyNum = (num) => {

  const options = {
    style: 'currency',
    currency: 'CNY',
  };
  return num.toLocaleString("zh-CN", options);
}
// 选择卡
const chooseCard = (item) => {
  from.card_id = item.id
}
// 加载
const loading = ref(false);
const showkeyboard = ref(true);
// 失去焦点
const onBlur = () => {
  showkeyboard.value = true;
};
// 获取焦点
const onFocus = () => {
  showkeyboard.value = false;
};
// 支出收入逻辑
const chooseAcountType = (e) => {
  const clickedElement = e.target;
  if (
    clickedElement.classList.contains("type_item") ||
    clickedElement.closest(".type_item")
  ) {
    const acountType = clickedElement.getAttribute("acountType");
    from.acountType = acountType;
  }
};
// end

//acountType
const changeType = (item, index) => {
  typeList.map((item) => {
    item.choose = false;
  });
  typeList[index].choose = true;
  from.type = index;
};
// end

// 表单逻辑开始
const from = reactive({
  acountType: 1,
  beginTime: [],
  number: "",
  type: 0,
  remask: null,
  card_id: null,//银行卡id
});
const onInput = (value) => {
  //   如果第一次输入点的话在前面加上0
  if (value == "." && from.number == "") {
    from.number = "0.";
    return;
  }
  // 判断是否存在.
  if (value == "." && from.number.indexOf(".") != -1) {
    return;
  }
  if (from.number.length >= 8) {
    showToast("超出最长限制");
    return;
  }
  from.number += value;
};
const onDelete = () => {
  from.number = from.number.slice(0, -1);
};
// 输入完成
const onComplete = async () => {
  loading.value = true;
  // 判断是否输入
  if (from.number == "") {
    showToast("请输入金额");
    loading.value = false;
    return;
  }
  if (!from.card_id) {
    showToast("请选择消费的卡");
    loading.value = false;
    return;
  }
  // 获取当前时分秒
  const date = new Date();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();
  let formateCreatedDate = from.beginTime.join("-");
  // 某天的时间戳
  const createdTime_ = new Date(formateCreatedDate);
  createdTime_.setHours(0, 0, 0, 0)//防止不是当天记账出现时间戳偏移问题
  const createdTime = createdTime_.getTime()
  console.log("记账时间的时间戳", createdTime);
  // 格式化beginTime 某天什么时候的时间戳
  let formateBeginTime =
    from.beginTime.join("-") + " " + hour + ":" + minute + ":" + second;
  const beginTime = new Date(formateBeginTime).getTime();
  // 本地存储获取id
  const userInfo = localStorage.getItem("userInfo");
  const uid = JSON.parse(userInfo).id;
  //  uid, createdDate, acountType, beginTime, number, remask, type
  // 如果number不存在小数点或者存在小数点了小数位不够两位在后面添加0
  if (!/\./.test(from.number)) {
    // 如果字符串中不存在小数点，则在末尾添加两位小数
    from.number += ".00";
  } else if (/\.\d$/.test(from.number)) {
    // 如果字符串中存在小数点，但小数位数不够两位，则在末尾添加一位小数
    from.number += "0";
  } else if (!/\.\d{2}$/.test(from.number)) {
    // 如果小数位数超过两位，则截取前两位小数
    from.number = from.number.replace(/(\.\d{2})\d*/, "$1");
  }

  const params = {
    uid: uid,
    createdDate: createdTime,//记账时间的时间戳 包含时分秒
    beginTime,//记账时间的时间戳 不包含时分秒 就是记录当天的0点0分0秒
    number: from.number,
    remask: from.remask,
    type: from.type,
    acountType: from.acountType,
    card_id: from.card_id,
  };
  // 发送请求
  const json = await addAccountReq(params);
  loading.value = false;
  if (json.status != 200) {
    showToast("获取数据失败，请刷新重试！");
    return;
  }
  showToast("添加成功！");
  emits("successAdd");
};
// 获取时间
const getTime = () => {
  console.log(new Date().toLocaleString());
  //   获取年月日
  const date = new Date();
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  from.beginTime = [year, month, day];
  currentDate.value = [year, month, day];
};
// 逻辑结束
const typeList = reactive([
  {
    name: "餐饮",
    icon: "icon-canyin",
    color: "#f56c6c",
    choose: true,
  },
  {
    name: "购物",
    icon: "icon-gouwuchekong",
    color: "#e6a23c",
    choose: false,
  },
  {
    name: "服饰",
    icon: "icon-fushi",
    color: "#409eff",
    choose: false,
  },
  {
    name: "交通",
    icon: "icon-gongjiao",
    color: "#409eff",
    choose: false,
  },
  {
    name: "房租",
    icon: "icon-fangzu",
    color: "#409eff",
    choose: false,
  },
  {
    name: "水费",
    icon: "icon-shuifei",
    color: "#409eff",
    choose: false,
  },
  {
    name: "电费",
    icon: "icon-dianfeijiaofei",
    color: "#409eff",
    choose: false,
  },
  {
    name: "工资",
    icon: "icon-yuangonggongzi",
    color: "#409eff",
    choose: false,
  },
  {
    name: "返现",
    icon: "icon-qita",
    color: "#409eff",
    choose: false,
  },
  {
    name: "其他",
    icon: "icon-qita",
    color: "#409eff",
    choose: false,
  },
]);

// 选择日期的逻辑
const show = ref(false);
const currentDate = ref([]);
//确定选中
const onConfirm = ({ selectedValues }) => {
  show.value = false;
  console.log(selectedValues);
  from.beginTime = selectedValues;
};
// 取消选中
const onCancel = () => {
  show.value = false;
  // 重置时间
  currentDate.value = from.beginTime;
};
// end

onMounted(() => {
  getTime();
  queryCardList_()
});
</script>

<style scoped lang="scss">
.add_acount {
  .type_time {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .type {
      display: flex;
      align-items: center;

      .type_item {
        padding: 0.1082rem 0.3851rem;
        background-color: #f0f0f0;
        border-radius: 0.3846rem;
        border: 0.0256rem solid #f0f0f0;
        color: #a5a2a2;
        margin: 0 0.1282rem;
      }

      .choose_type_in {
        color: #38be77;
        background-color: #eafbf5;
        border: 0.0256rem solid #38be77;
      }

      .choose_type_out {
        color: #f0b73a;
        background-color: #fdf8eb;
        border: 0.0256rem solid #f0b73a;
      }
    }

    .time {
      display: flex;
      align-items: center;
      font-size: 0.3077rem;
      background-color: #f0f0f0;
      padding: 0.0513rem 0.2282rem;
      border-radius: 0.2051rem;

      .icon {
        // 旋转
        margin-left: 0.1282rem;
        transform: rotate(90deg) translateX(-2px);
      }
    }
  }

  .custom_title_money {
    font-size: 0.5231rem;
    font-weight: bold;
    vertical-align: top;
  }

  .custom_title_money_tip {
    font-size: 0.4231rem;
    font-weight: bold;
    color: #d4d2d4;
    vertical-align: top;
  }

  .useType {
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    grid-gap: 0.3846rem;
    grid-template-rows: auto;
    margin-top: 0.9128rem;

    .use_item {
      text-align: center;
      display: flex;
      flex-direction: column;
      justify-content: center;

      .iconfont {
        font-size: 0.5641rem;
      }

      .choose_icon {
        color: #38be77;
      }
    }
  }

  .use_card {
    position: relative;

    .custom-indicator {
      position: absolute;
      right: 5px;
      bottom: 5px;
      padding: 2px 5px;
      font-size: 12px;
      background: rgba(0, 0, 0, 0.1);
    }

    .use_card_item {
      border-radius: .2051rem;
      display: flex;
      align-items: center;
      padding: 0.3846rem 0.2282rem;
      background-image: url("@/assets/Ornament.png");


      .card_img {
        width: 1.2821rem;
        height: 1.2821rem;
        border-radius: 50%;
        overflow: hidden;

        img {
          width: 100%;
          height: 100%;
        }
      }

      .card_info_name {
        font-size: .4103rem;
        font-weight: 500;
        color: rgba(29, 32, 39, 1);
        flex: 1;
        margin-left: .2564rem;
      }

      .card_info_money {
        font-size: .3077rem;
        font-weight: 700;
        color: rgba(71, 146, 75, 1);
      }
    }
  }

  .wrapper {
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
